<template>
  <div class="card" style="margin-bottom: 10px;">
    <el-input v-model="name" prefix-icon="Search" style="width: 300px; margin-right: 10px" placeholder="请输入纪念品名称查询"></el-input>
    <el-button type="primary" @click="load(1)">查询</el-button>
    <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
  </div>


  <div style=" margin-left: 50px ">
    <el-row>
      <el-col
          v-for="(item, index) in tableData"
          :key="item"
          :span="7"
          :offset="index % 3 > 0 ? 1 : 0"
      >
        <el-card :body-style="{ padding: '0px' }"  style="margin-top: 40px">
          <img
              :src="item.picture || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'"
              style="max-width: 100%; max-height: 300px; object-fit: contain;"
              class="image"
          />
          <div style="padding: 14px; display: flex; justify-content: space-between; align-items: center;">
            <span>{{ item.name }}</span>
            <span>{{ item.price  }} $ </span>
          </div>
          <div class="bottom" style="display: flex; justify-content: right; align-items: center;" >
            <el-input-number
                style="width: 100px; margin: 10px"
                v-model=item.num :min="1" :max="10" @change="handleChange(item)"/>
            <el-button class="button" style="margin-right: 10px" type="primary" @click="addShoppingCar(item)" >加入订单</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>


  <div style="margin: 10px 0">
    <div class="example-pagination-block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script >

import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: 'UserGoods',
  data() {
    return {
      currentDate: new Date(),
      name: '',
      user : JSON.parse(localStorage.getItem('honey-user')),
      tableData: [],
      pageNum: 1,
      pageSize: 6,
      total: 0,


    }
  },
  created() {
    this.load(this.pageNum)
  },
  methods: {
    reset() {
      this.name = ''
      this.load(this.pageNum)
    },
    load(pageNum) { // 分页查询
      if (pageNum) {
        this.pageNum = pageNum;
      }
      request.get('/goods/selectByPage', {
        params: { pageNum: this.pageNum, pageSize: this.pageSize, name: this.name, state:1 }
      }).then(res => {
        if (res && res.data && typeof res.data === 'object') {
          this.tableData = (res.data.list || []).map(item => ({
            ...item,
            num: 1 // 初始化 num 为 1
          }));
          this.total = res.data.total || 0;
          console.log("纪念品数据:", this.tableData);
        } else {
          console.error("无效的响应数据:", res);
          ElMessage.error('获取纪念品数据失败，请稍后再试');
        }
      }).catch(err => {
        console.error("获取纪念品数据失败:", err);
      });
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum);
    },
    handleChange(item) {
      console.log('购买数量变化:', item.num);
    },
    addShoppingCar(item) {
      const price = item.price * item.num; // 计算总价
      ElMessageBox.confirm(`确定要将 ${item.num} 件 ${item.name} 加入购物车吗？总价为 ${price} $`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        request.post('/order/add', {
          goodsName: item.name,
          number: item.num, // 使用用户选择的商品数量
          price : item.price * item.num, // 单价
          userId: this.user.id,

        }).then(response => {
          if (response.code === 1) {
            ElMessage.success('加入购物车成功');
          } else {
            ElMessage.error(response.msg);
          }
        });

      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消加入购物车',
        });
      });
    }

  }
}

</script>

<style>
.price {
  font-size: 12px;
  color: #cb2140;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
}

.image {
  width: 100%;
  display: block;
}
</style>
